package com.cxm.weilai.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * excel 导入工具类
 *
 * @author jackie.cheng
 */
public class ExcelUtils {

    private static Log logger = LogFactory.getLog(ExcelUtils.class);
    public static final String SIMPLE_FORMAT = "yyyy-MM-dd";

    /**
     * 根据文件路径加载
     */
    public static Workbook loadExcelData(String filePath) {
        File dstFile = new File(filePath);
        String fileType = dstFile.getName().substring(dstFile.getName().lastIndexOf(".") + 1).toLowerCase();
        FileInputStream inputStream = null;
        Workbook wb = null;

        try {
            inputStream = new FileInputStream(dstFile);
            // 文件格式
            if ("xls".equals(fileType)) { // 2003
                wb = new HSSFWorkbook(inputStream);
            } else if ("xlsx".equals(fileType)) { // 2007
                wb = new XSSFWorkbook(inputStream);
            }
        } catch (IOException e1) {
            logger.error(e1.getMessage(), e1);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e1) {
                    logger.error(e1.getMessage(), e1);
                }
            }
        }

        return wb;
    }

    /**
     * 根据文件、文件名加载
     */
    public static Workbook loadExcelData(File file, String filename) {
        FileInputStream inputStream = null;
        Workbook wb = null;
        try {
            inputStream = new FileInputStream(file);
            // 文件格式
            if (filename.endsWith("xls")) { // 2003
                wb = new HSSFWorkbook(inputStream);
            } else if (filename.endsWith("xlsx")) { // 2007
                wb = new XSSFWorkbook(inputStream);
            }
        } catch (IOException e1) {
            logger.error(e1.getMessage(), e1);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e1) {
                    logger.error(e1.getMessage(), e1);
                }
            }
        }

        return wb;
    }

    /**
     * 获取单元格的值
     */
    @SuppressWarnings("deprecation")
    public static String getCellValue(Cell cell) {
        String cellVal = null;
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    cellVal = cell.getStringCellValue().trim();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        double date = cell.getNumericCellValue();
                        cellVal = parseDateToString(SIMPLE_FORMAT, HSSFDateUtil.getJavaDate(date));
                    } else {
                        cellVal = getCellValue(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    Boolean bool = cell.getBooleanCellValue();
                    cellVal = bool ? "TRUE" : "FALSE";
                    break;
                default:
                    cellVal = cell.getStringCellValue().trim();
            }
        }
        return cellVal;
    }

    /**
     * 获取double类型单元格的值
     */
    public static String getCellValue(Double cellVal) {
        DecimalFormat formater = new DecimalFormat();

        formater.setMaximumFractionDigits(10);
        formater.setGroupingSize(0);
        formater.setRoundingMode(RoundingMode.FLOOR);
        String celval = formater.format(cellVal);

        return celval;
    }

    /**
     * 解析Date to string
     */
    public static String parseDateToString(String dateFormat, Date date) {
        DateFormat df = new SimpleDateFormat(dateFormat);
        return df.format(date);
    }

    /**
     * 解析String to Date
     */
    public static Date parseStringToDate(String str) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat(SIMPLE_FORMAT);
        Date date = new Date();
        date = dateFormat.parse(str);
        return date;
    }

    /**
     * start time
     */
    public static double getInitTime() {
        return System.nanoTime();
    }

    /**
     * duration time
     */
    public static double getDurationFrom(double startTime) {
        double endTime = System.nanoTime();
        return (endTime - startTime);
    }
}
